import {Row, Col, Input, Modal, Tabs, Pagination, Select, Menu, Button, Dropdown, Icon, Form, message, Spin} from 'antd';
// import Row from '../../../_antd1.11.2/Row';
// import Col from '../../../_antd1.11.2/Col';
// import Input from '../../../_antd1.11.2/Input';
// import Modal from '../../../_antd1.11.2/Modal';
// import Tabs from '../../../_antd1.11.2/Tabs';
// import Pagination from '../../../_antd1.11.2/pagination';
const TabPane = Tabs.TabPane;
// import Select from '../../../_antd1.11.2/Select';
const Option = Select.Option;
// import Menu from '../../../_antd1.11.2/menu';
const SubMenu = Menu.SubMenu;
const MenuItemGroup = Menu.ItemGroup;
// import Button from '../../../_antd1.11.2/Button';
// import Dropdown from '../../../_antd1.11.2/Dropdown';
// import Icon from '../../../_antd1.11.2/Icon';
// import Form from '../../../_antd1.11.2/Form'
const FormItem = Form.Item;
// import message from '../../../_antd1.11.2/message'
import cloneDeep from 'lodash/cloneDeep';
const  _  =  require('lodash');
import forEach from 'lodash/forEach';
import isEmpty from 'lodash/isEmpty'
import uniq from 'lodash/uniq'
import isEqual from 'lodash/isEqual';

import WeaInputSearch from '../../wea-input-search';
import WeaSearchBrowserBox from '../wea-search-browser-box';
import WeaAssociativeSearchMult from '../wea-associative-search-mult'
import Operation from './operation';
import WeaBrowserMutiRight from '../wea-browser-muti-right';
import WeaTools from '../../wea-tools';
import WeaBrowserMutiLeft from '../wea-browser-muti-left';
import WeaBrowserTree from '../wea-browser-single-tree/WeaBrowserTree';
import WeaBrowserSearch from '../../wea-browser-search';
import WeaSelect from '../../wea-select';
import WeaNewScroll from '../../wea-new-scroll';
// import Spin from '../../../_antd1.11.2/Spin';
import uniqBy from 'lodash/uniqBy'
import debounce from 'lodash/debounce'
import isArray from 'lodash/isArray'

const initialState = {
    showSearchAd:false,
    count: 0,
    visible: false,
    currentPage: 1,
    inputValue: '',
    searchPara: {},
    checkStrictly: true,
    browserConditions: [],
    leftListSelectedKeys: [],
    leftListSelectedData: [],
    leftTreeCheckedKeys:[],
    leftTreeCheckedData:[],
    loadAllTreeData: false,
    selectedValue: null,
    displayType: '',
    loading: true,
}

class Main extends React.Component {
    static Operation = Operation;
    static defaultProps = {
        mult:true,
    }
    constructor(props) {
        super(props);
        const {dataUrl}=this.props;
        this.state = {
            visible: null,
            activeKey: this.getDefaultKey(props.tabs),
            initialShowSearchAd:false,
            showSearchAd:false,
            isClearData: false,
            rightCheckedKeys: [], //右侧选择的keys
            rightDatas:[],  // 右侧展示的数据
            leftListSelectedKeys:[], // 左侧table选择的keys
            leftListSelectedData: [], // 左侧table选择的数据
            leftTreeCheckedKeys:[], // 左侧tree选择的keys
            leftTreeCheckedData:[], // 左侧tree选择的数据
            selectedData: {}, // 搜索按钮选中的数据
            searchKeys:[], // 搜索按钮选择的keys
            listDatas: [],
            currentPage: 1,
            pageSize: props.pageSize || 20,
            count: 0,
            url: dataUrl,
            inputValue: '',
            searchPara: {},
            dataKey:'',
            noPgTableData:[],
            inputId: '',
            inputName: '',
            inputTop: [],
            inputBottom: [],
            browserConditions: [],
            displayType: 'list', // list/tree
            contentType: 1, // 数据展示的类别
            quickSearch: '',
            defaultExpandedKeys:[],
            hiddenIds:'',
            checkStrictly: true,
            loadAllTreeData: false,
            selectedValue: null,
            loading: true,
            dropmenuDatas: [],
        }
    }
    componentDidMount() {
        // 默认显示数据
        if (!isEmpty(this.props.replaceDatas)) {
            this.replaceSearchValues(this.props.replaceDatas);
        }
    }
    componentWillReceiveProps(nextProps){
        if (this.props.value !== nextProps.value && isEmpty(nextProps.value)) {
            this.setState({isClearData: !this.state.isClearData});
            this.handleClear();
        }
        if (!isEqual(this.props.replaceDatas, nextProps.replaceDatas)) {
            this.replaceSearchValues(nextProps.replaceDatas);
        }
    }
    setLoading(bool) {
        this.setState({loading: bool});
    }
    formatInput(columns) {
        let inputId, inputName, inputTop = [], inputBottom = [];
        if (!isEmpty(columns)) {
            columns.forEach((item) => {
                if (item.isInputCol === 'true') {
                    inputName = item.dbField || item.dataIndex
                }
                if (item.isPrimarykey === 'true') {
                    inputId = item.dbField || item.dataIndex
                }
                if (item.hide === 'false') {
                    if (item.showType === '1') {
                        inputTop.push(item.dbField || item.dataIndex)
                    }
                    if (item.showType === '0') {
                        inputBottom.push(item.dbField || item.dataIndex)
                    }
                }
            })
        }
        if (!inputId) {
            inputId = 'id';
        }
        if (!inputName) {
            inputId = 'name';
        }
        this.setState({
            inputName: inputName,
            inputId: inputId,
            inputTop: inputTop,
            inputBottom: inputBottom,
        });
    }
    datakeyTodatas(newDataKey,newCurrent,min,max,cb) {
        WeaTools.callApi("/api/ec/dev/table/datas", 'POST', {dataKey: newDataKey, min: min, max: max}).then(data => {
            this.formatInput(data.columns);
            if (cb) cb();
            if (isArray(data.datas)) {
                this.setState({
                    listDatas: data.datas,
                });
            }
            if (data.count) {
                this.setState({
                    count: data.count,
                });
            }
            this.setLoading(false);
        }, (e) => {
            console.log('api /api/ec/dev/table/datas error', e)
        }),
        WeaTools.callApi("/api/ec/dev/table/counts",'POST',{ dataKey: newDataKey }).then(data => {
            this.setState({
                count: data.count,
            });
        }, (e) => {
            console.log('api /api/ec/dev/table/counts error', e)
        })
    }
    formatUrl(url, params) {
        if (url && !isEmpty(params)) {
            url = `${url}${WeaTools.getFd(params)}`;
        }
        return url;
    }
    getData(url, currentPage, hasPagination = false, searchPara, cb, companyId) {
        this.setLoading(true);
        const {pageSize, count} = this.state;
        url = url || this.state.url;
        let params = searchPara || this.state.searchPara || {};
        params = {...params};
        currentPage = currentPage || this.state.currentPage;
        if (hasPagination) {
            params['min'] = (currentPage - 1) * pageSize + 1;
            params['max'] = currentPage * pageSize;
        }
        params['pageSize'] = pageSize;
        if(params['max'] && currentPage > 1) {
            if (params['max'] > count) params['max'] = count;
        }
        if (this.props.type=='194'|| this.props.type =='57') {
            companyId = companyId || this.state.companyId;
            if (companyId) params['virtualCompanyid'] = companyId;
        }
        WeaTools.callApi(this.formatUrl(url, params),'GET').then(data=> {
            if (data.type == 1){//分页table
                const dataKey = data.datas;
                this.setState({
                    displayType: 'list',
                    contentType: data.type,
                });
                this.datakeyTodatas(dataKey,currentPage,params['min'],params['max'], cb);
            }
            if (data.type == 2){//不分页的table
                this.setState({
                    displayType: 'list',
                    contentType: data.type,
                    listDatas: data.datas,
                });
                this.formatInput(data.columns);
                if (cb) cb();
                this.setLoading(false);
            }
            if (data.type == 3){//树
                this.formatInput(data.columns);
                if (cb && data.columns) cb();
                let keysArr = [];
                const {topPrefix} = this.props;
                keysArr.push(`${topPrefix}0-${data.datas.id}`);
                this.setState({
                    displayType: 'tree',
                    contentType: data.type,
                    treeData: data.datas,
                    defaultExpandedKeys: keysArr,
                    loadAllTreeData: data.isLoadAll,
                })
                if ((this.props.type=='194'|| this.props.type =='57') && !companyId) {
                    const companysDefault = this.getCompany(data.companys);
                    this.setState({
                        dropmenuDatas: data.companys,
                        companyName: companysDefault.name,
                        companyId: companysDefault.companyid,
                    })
                }

                this.setLoading(false);
            }
            if (data.type == 4){//自定义分页的list
                this.formatInput(data.columns);
                this.setState({
                    displayType: 'list',
                    contentType: data.type,
                    listDatas: data.datas,
                    count: data.total
                })
                if (cb) cb();
                this.setLoading(false);
            }
        }).then((result)=>{
        })
    }
    getCompany(datas, key) {
        for (let i=0,leng=datas.length;i<leng;i++) {
            if (key) {
                if (key == datas[i].companyid) {
                    return datas[i];
                }
            } else {
                if(Number(datas[i].companyid) >= 0){
                    return datas[i];
                }
            }
        }
    }
    getDefaultKey(tabs) {
        let key = '';
        if (!isEmpty(tabs)) {
            tabs.forEach((tab)=> {
                if (tab.selected) {
                    key = tab.key;
                }
            })
            if (!key) {
                key = tabs[0].key;
            }
        }
        return key;
    }
    onTabsChange(activeKey) {
        const {resetFields, setFieldsValue} = this.props.form;
        this.setState({browserConditions: []});
        resetFields();
        let url = this.getUrl(false, activeKey);
        const quickSearch = this.state.quickSearch || 'name';
        this.setState({
            url,
            activeKey,
            count: 0,
            currentPage: 1,
            inputValue: this.defaultConditionParams[quickSearch] || '',
            selectedValue: this.defaultConditionParams['date2during'] || '',
            showSearchAd: false,
            browserConditions: this.browserConditionsBk,
            searchPara: this.defaultConditionParams,
        });
        setFieldsValue(this.defaultConditionParams);
        this.getData(url, 1, true, this.defaultConditionParams);
        this.refs.weaSrcoll && this.refs.weaSrcoll.scrollerToTop();
    }
    onPageChange(page) {
        this.getData('', page, true);
        this.setState({currentPage: page});
        this.refs.weaSrcoll && this.refs.weaSrcoll.scrollerToTop();
    }
    getUrl(searched = false, activeKey) {
        activeKey = activeKey || this.state.activeKey;
        const {tabs, dataUrl} = this.props;
        let url = dataUrl;
        let tab = {};
        if (!isEmpty(tabs)) {
            tab = tabs.filter(m=>m.key==activeKey)[0];
        }
        if (searched && !isEmpty(tabs)) {
            tabs.forEach((t)=> {
                if (t.isSearch) {
                    tab = t;
                    this.setState({activeKey: t.key});
                }
            })
        }
        if (tab.url) {
            url = tab.url;
        }
        if (!isEmpty(tab.dataParams)) {
            url = `${url}${WeaTools.getFd(tab.dataParams)}&`;
        }
        return url;
    }
    onSearchChange(v){
        const quickSearch = this.state.quickSearch || 'name';
        const {setFieldsValue} = this.props.form;
        let params = this.getFields();
        params[quickSearch] = v;
        if (this.state.selectedValue) params['date2during'] = this.state.selectedValue;
        let url = this.getUrl(true);
        this.getData(url, 1, true, params); // 搜索获取数据
        setFieldsValue(params); // 高级搜索数据联动
        this.setState({
            url,
            inputValue: v,
            showSearchAd: false,
            searchPara: params,
        });
        this.refs.weaSrcoll && this.refs.weaSrcoll.scrollerToTop();
    }
    goSearch=(e)=>{
        const {tabs} = this.props;
        const quickSearch = this.state.quickSearch || 'name';
        e.preventDefault();
        let params = this.getFields();
        let url = this.getUrl(true);
        this.getData(url, 1, true, params); // 搜索获取数据
        this.setState({
            url,
            searchPara: params,
            showSearchAd:false,
            inputValue: params[quickSearch] || '',
        });
        if (params['date2during']) {
            this.setState({selectedValue: params['date2during']});
        }
        this.refs.weaSrcoll && this.refs.weaSrcoll.scrollerToTop();
    }
    getFields() {
        const {validateFields} = this.props.form;
        let params = {};
        validateFields((errors, object) => {
            if (!!errors) {
                return;
            }
            let newObject = cloneDeep({...object,...conditionParamsBK});
            forEach(newObject, (value, key) => {
                if (value) params[key] = value;
            })
        });
        return params;
    }
    showModal() {
        this.setState({visible: true});
    }

    setShowSearchAd(bool){
        const {showSearchAd}=this.state;
        this.setState({showSearchAd:bool, initialShowSearchAd:true})
    }
    onCustomClick = (e) => {
        e.preventDefault();
        const {memorise} = this.props;
        if (memorise) {
            const {searchKeys, selectedData} = this.state;
            this.onBrowerClick(searchKeys, selectedData);
        } else {
            this.onBrowerClick();
        }
    }
    onBrowerClick = (keys, selectedObj) => {
        const {resetFields, setFieldsValue} = this.props.form;
        resetFields(); // 重置高级搜索
        let url = this.getUrl();
        const {conditionURL} = this.props;
        WeaTools.callApi(conditionURL,'GET').then(data=>{
            let quickSearch;
            if (!isEmpty(data.conditions)) {
                data.conditions.forEach((item)=> {
                    if (item.isQuickSearch) {
                        quickSearch = item.domkey[0];
                    }
                })
            }
            const params = WeaTools.getParamsByConditions(data.conditions);
            conditionParamsBK = params;
            setFieldsValue(params);
            this.browserConditionsBk = data.conditions;
            this.defaultConditionParams = {...params};
            this.setState({
                browserConditions: data.conditions,
                quickSearch, url,
                searchPara: params,
                inputValue: params[quickSearch] || '',
                selectedValue: params['date2during'] || '',
            });
            this.getData(url, 1, true, params, ()=> {
                // reset selected data
                this.onBrowerChange(keys, selectedObj, false);
            });
        });
        if (isEmpty(keys)) {
            this.setState({searchKeys: [], selectedData: {}, rightDatas: []});
        }
        this.showModal();
    }
    handleOk() {
        const {rightDatas, inputId, inputName, contentType} = this.state;
        const {maxLength} = this.props;
        let values = [];
        let selectedData = {};
        if (!isEmpty(rightDatas)) {
            if (maxLength && maxLength < this.count(rightDatas, true)) {
                window.alert(`所选的数量不能超过${maxLength}!`);
                return;
            }
            rightDatas.forEach((item)=> {
                item.id = item[inputId];
                item.name = item[inputName +　'span'] || item[inputName];
                selectedData[item.id] = item;
                values.push(item.id);
            });
        }
        this.setState({
            selectedData: selectedData,
            visible: false,
            searchKeys: values
        });
        this.throwCurrentState(values.join(','), this.formatThrowDatas(rightDatas));
        this.setState({activeKey: this.getDefaultKey(this.props.tabs)});
        this.setState(initialState);//初始化浏览框
        this.refs.browserRight && this.refs.browserRight.reset();
    }
    handleCancel() {
        this.setState({activeKey: this.getDefaultKey(this.props.tabs)});
        this.setState(initialState);//初始化浏览框
        this.refs.browserRight && this.refs.browserRight.reset();
    }
    handleClear() {
        this.setState({
            visible: false,
            isClearData: !this.state.isClearData,
            rightDatas: [],
            rightCheckedKeys: [],
            leftTreeCheckedKeys: [],
            leftListSelectedKeys: [],
            leftListSelectedData: [],
            leftTreeCheckedData: [],
            selectedData: {},
            searchKeys: []
        });
        this.setState({activeKey: this.getDefaultKey(this.props.tabs)});
        this.setState(initialState);//初始化浏览框
        this.throwCurrentState('', []);
        this.refs.browserRight && this.refs.browserRight.reset();
    }
    set(datas) {
        this.replaceSearchValues(datas);
    }
    replaceSearchValues(datas = []) {
        let searchKeys = [], selectedData = {};
        datas.forEach((item) => {
            searchKeys.push(item.id);
            selectedData[item.id] = item;
        })
        this.setState({searchKeys:searchKeys, selectedData: selectedData});
        let ids = uniq(searchKeys).join(',');
        this.setState({hiddenIds: ids});
        // this.throwCurrentState(searchKeys.join(','), datas);
    }
    formatThrowDatas(datas) {
        const {inputId, inputName} = this.state;
        const res = [];
        if (!isEmpty(datas)) {
            datas.forEach(d => {
                res.push({
                    id: d[inputId] || d.id || '',
                    name: d[inputName + 'span'] || d[inputName] || d.name || ''
                })
            })
        }
        return res;
    }
    onBrowerChangeHandler(values, datas) {
        this.setState({searchKeys:values, selectedData: datas});
        const throwDatas = [];
        if (!isEmpty(values)) {
            values.forEach(v => {
                throwDatas.push(datas[v]);
            })
        }
        this.throwCurrentState(values.join(','), this.formatThrowDatas(throwDatas));
    }
    onBrowerChange(values, datas, needOnchange = true) {
        const {destUrl} = this.props;
        if (!isEmpty(values)) {
            values = uniq(values);
            WeaTools.callApi(`${destUrl}selectids=${values.join(',')}`,'GET').then((res)=> {
                this.setState({searchKeys:values, selectedData: datas, rightDatas: res.datas});
                if(needOnchange) this.throwCurrentState(values.join(','), this.formatThrowDatas(res.datas));
            }, (e) => {
                console.log('api /api/workflow/browser01/destData error', e)
            })
        } else {
            this.setState({searchKeys: [], selectedData: {}, rightDatas: []});
            if(needOnchange) this.throwCurrentState('', []);
        }
    }
    onRightDoubleClick(key) {
        const {rightDatas, inputId} = this.state;
        const newRightDatas = rightDatas.filter(item => (item[inputId] || item.id)!== key);
        this.setState({rightDatas: newRightDatas, rightCheckedKeys: []});
    }
    onleftDoubleClick(data) {
        const {rightDatas} = this.state;
        this.setState({
            rightDatas: rightDatas.concat(data),
            rightCheckedKeys:[],
            leftListSelectedData:[],
            leftTreeCheckedData:[],
            leftTreeCheckedKeys:[],
            leftListSelectedKeys:[]
        });
    }
    onleftTreeDoubleClick(data) {
        const {rightDatas} = this.state;
        const {destUrl} = this.props;
        WeaTools.callApi(`${destUrl}selectids=${data[0].id}`,'GET').then((res)=> {
            this.setState({
                rightDatas: rightDatas.concat(res.datas),
                rightCheckedKeys:[],
                leftListSelectedData:[],
                leftTreeCheckedData:[],
                leftTreeCheckedKeys:[],
                leftListSelectedKeys:[]
            });
        })
    }
    moveTo = (direction) => {
        const {rightDatas, rightCheckedKeys, listDatas, inputId} = this.state;
        const {destUrl} = this.props;
        if (direction === 'right') {
            const {leftListSelectedData, leftTreeCheckedData, leftTreeCheckedKeys} = this.state;
            let datas = leftListSelectedData;
            if (leftTreeCheckedData.length > 0 ) {
                WeaTools.callApi(`${destUrl}selectids=${leftTreeCheckedKeys.join(',')}`,'GET').then((res)=> {
                    datas = datas.concat(res.datas);
                    this.setState({
                        rightDatas: rightDatas.concat(datas),
                        rightCheckedKeys:[],
                        leftListSelectedData:[],
                        leftTreeCheckedData:[],
                        leftTreeCheckedKeys:[],
                        leftListSelectedKeys:[]
                    });
                })
            } else {
                this.setState({
                    rightDatas: rightDatas.concat(datas),
                    rightCheckedKeys:[],
                    leftListSelectedData:[],
                    leftTreeCheckedData:[],
                    leftTreeCheckedKeys:[],
                    leftListSelectedKeys:[]
                });
            }
        }
        if (direction === 'left') {
            const newRightDatas = rightDatas.filter(item => !rightCheckedKeys.some(checkedKey => item[inputId] === checkedKey));

            this.setState({rightDatas: newRightDatas, rightCheckedKeys: []});
        }

        if (direction === 'allToLeft') {
            this.setState({rightDatas: [], rightCheckedKeys: []});
        }

        if (direction === 'allToRight') {
            if (this.leftListAllActive()) {
                this.setState({
                    rightDatas: rightDatas.concat(listDatas),
                    rightCheckedKeys:[],
                    leftListSelectedData:[],
                    leftTreeCheckedData:[],
                    leftTreeCheckedKeys:[],
                    leftListSelectedKeys:[],
                })
            }
        }
    }

    moveToLeft = () => this.moveTo('left')
    moveToRight = () => this.moveTo('right')
    moveAllToLeft = () => this.moveTo('allToLeft')
    moveAllToRight = () => this.moveTo('allToRight')

    count(rightDatas = [], rNum = false) {
        const {inputId} = this.state;
        let count = 0;
        let ids = [];
        rightDatas.forEach((item)=> {
            ids.push(item[inputId]);
        })
        count += uniq(ids).length;
        if (rNum) return count;
        return count > 0 ? `(${count})` : '';
    }
    renderTab() {
        const {tabs} = this.props;
        let TabPanes = [];
        if (!isEmpty(tabs)) {
            tabs.forEach((tab) => {
                TabPanes.push(<TabPane tab={tab.name} key={tab.key}></TabPane>)
            })
            return (
                <Tabs
                    onChange={this.onTabsChange.bind(this)}
                    activeKey={this.state.activeKey}>
                        {TabPanes}
                </Tabs>
            )
        }
    }
    leftListAllActive() {
        const {rightDatas, listDatas, inputId} = this.state;
        let bool = true;
        if (isEmpty(listDatas)) bool = false;
        if (!isEmpty(listDatas) && !isEmpty(rightDatas)) {
            bool = listDatas.filter((l) => !rightDatas.some(r => l[inputId] === r[inputId])).length !== 0;
        }
        return bool;
    }
    resetFields() {
        const {setFieldsValue} = this.props.form;
        const {browserConditions} = this.state;
        const fields = {};
        browserConditions.forEach((c) => {
            let ct = c.conditionType.toUpperCase();
            let domkey = c.domkey[0];
            const filterKeys = [1, -1, '1', '-1'];
            if (ct === 'BROWSER') {
                if (!isEmpty(c.browserConditionParam) && filterKeys.indexOf(c.browserConditionParam.viewAttr) == -1) {
                    fields[domkey] = undefined;
                    conditionParamsBK[domkey] = '';
                }
            } else {
                if (filterKeys.indexOf(c.viewAttr) == -1) {
                    fields[domkey] = undefined;
                    conditionParamsBK[domkey] = '';
                }
            }
        })
        setFieldsValue(fields);
    }
    doChangeEvent=(v)=>{
        const {setFieldsValue} = this.props.form;
        let url = this.getUrl();
        let params = this.getFields();
        params.date2during = v;
        this.getData(url, 1, true, params);
        this.setState({selectedValue:v});
        setFieldsValue({date2during: v});
    }
    topComponents =()=> {
        const {browserConditions,selectedValue} = this.state;
        const {type} = this.props;
        const tab = this.renderTab();
        const addSelect = ()=>{
            let options = [];
            browserConditions &&　browserConditions.forEach((m)=>{
                if (m.domkey[0]=='date2during') {
                    options = m.options;
                }
            })
            if (options.length > 0) {
                return (
                    <WeaSelect
                        style={{width: '100px'}}
                        value={selectedValue}
                        options={options}
                        onChange={this.doChangeEvent}
                    />
                );
            }
        }
        if (tab) {
            return (
                <WeaBrowserSearch
                    addSelect={type=='152' || type=='171' ? addSelect():''}
                    tabs={tab}
                    searchType={[]}
                />
            )
        }
    }
    reset() {
        this.resetFields();
        this.setState({inputValue: ''});
    }
    onSelect(item) {
        let company = this.getCompany(this.state.dropmenuDatas, item.key);
        this.setState({
            companyid: item.key,
            companyName: company.name,
        })
        let url = this.getUrl();
        this.getData(url, 1, false, {}, null, item.key);
    }
    renderDropmenu() {
        const {dropmenuDatas, companyName} = this.state;
        let menuItem = [];
        dropmenuDatas && dropmenuDatas.map((item)=>{
            menuItem.push(<Menu.Item key={item.companyid}>{item.name}</Menu.Item>);
            menuItem.push(<Menu.Divider />)
        });
        const typeMenu = (
            <Menu className="wea-browser-drop-menu" onSelect={this.onSelect.bind(this)}>
                {menuItem}
            </Menu>
        );
        return (
            <Row>
                <Col span={24}>
                    <Dropdown overlay={typeMenu} trigger={['click']}>
                        <a className="ant-dropdown-link" href="javascript:;">
                          <i className={'icon-toolbar-Organization-list'}/>
                                {companyName}
                                <Icon type="down" style={{float:"right"}}/>
                        </a>
                    </Dropdown>
                </Col>
            </Row>
        )
    }
    render() {
        let _this = this;
        const {icon,dropMenuIcon,iconBgcolor,title,browerType,dataUrl,recentUrl,sameDepUrl,mySubUrl,isaccount,min,max,virtualUrl,searchUrl,fieldName,contentHeight, modalStyle}=this.props;
        const {id,name,style,topPrefix,topIconUrl,otherPara,isMult,ifCheck,disabled,prefix,ifAsync,grouptree,resourcetree,value,type,mult,checkGroup,customized} = this.props;
        const {loading,visible,activeKey,showSearchAd, listDatas, inputValue, pageSize, count, currentPage,loadAllTreeData,leftTreeCheckedData} = this.state;
        const {displayType,rightDatas, rightCheckedKeys,leftTreeCheckedKeys,leftListSelectedKeys,selectedData,searchKeys} = this.state;
        const {checkStrictly,inputId, inputName, inputTop, inputBottom, contentType, treeData, defaultExpandedKeys, hiddenIds} = this.state;
        let titleEle = (
            <Row>
                <Col span="22" style={{paddingLeft:20,lineHeight:'48px'}}>
                    <div className="wea-hr-muti-input-title">
                        {iconBgcolor ? <div className="wea-workflow-radio-icon-circle" style={{background:iconBgcolor ? iconBgcolor : ""}}><i className={icon}/></div>
                        : <span style={{verticalAlign:'middle',marginRight:10}}><i className={icon}/></span>}
                        <span style={{verticalAlign:'middle'}}>{title}</span>
                    </div>
                </Col>
            </Row>
        );
        let inputArr = (
            <WeaAssociativeSearchMult
                {...this.props}
                inputName={inputName}
                inputId={inputId}
                style={this.props.inputStyle}
                datas={selectedData}
                selectedValues={searchKeys}
                isClearData={this.state.isClearData}
                type={type}
                clickCallback={this.onBrowerClick}
                onChange={this.onBrowerChangeHandler.bind(this)}
            />
        );
        const buttons = [
                <Button key="submit" type="primary" size="large" onClick={this.handleOk.bind(this) } disabled={this.count(rightDatas, true) == 0}>确 定{this.count(rightDatas)}</Button>,
                <Button key="clear" type="ghost" size="large" onClick={this.handleClear.bind(this)}>清 除</Button>,
                <Button key="back" type="ghost" size="large" onClick={this.handleCancel.bind(this)}>取 消</Button>];
        const searchsBox = this.getSearchs();
        const buttonsAd = this.getTabButtonsAd();
        const leftAllActive = displayType === 'list' && this.leftListAllActive();
        let sheight = initHeight = contentHeight;
        if (contentType === 1 || contentType === 4) sheight -= 35; //显示分页
        const {dataKey,noPgTableData} = this.state;
        let dom = inputArr;
        if (customized) {
            dom = (
                <div className="cursor-pointer" onClick={this.onCustomClick}>
                    {this.props.children}
                </div>
            )
        }
        let rightActive = false;
        if (leftListSelectedKeys && leftListSelectedKeys.length > 0) {
            rightActive = true;
        }
        if (leftTreeCheckedKeys && leftTreeCheckedKeys.length > 0) {
            rightActive = true;
        }
        const showDropMenu = type=='194'|| type =='57';
        if (showDropMenu && displayType === 'tree') sheight -= 37;
        return (
          <div>
            {dom}
            <input type="hidden" id={fieldName} name={fieldName} value={hiddenIds} />
            <Modal wrapClassName="wea-hr-muti-input wea-browser-muli wea-browser-modal"
                title={titleEle}
                zIndex={this.props.zIndex}
                width={modalStyle.width}
                maskClosable={false}
                visible={visible}
                onCancel={this.handleCancel.bind(this)}
                footer={buttons}>
                {this.topComponents()}
                <Spin spinning={loading}>
                    <div style={{padding: 10}}>
                        <div className='wea-hr-muti-input-left'>
                            <Row style={{height:"35px"}}>
                                <Col span="18">
                                    <WeaInputSearch placeholder={""} value={inputValue} onSearchChange={(v)=>{this.setState({inputValue: v})}} onSearch={this.onSearchChange.bind(this)}/>
                                </Col>
                                <Col span="6">
                                    <Button  className="wea-workflow-serch-condition" type="ghost" onClick={this.setShowSearchAd.bind(this,true)}>高级搜索</Button>
                                </Col>
                            </Row>
                            <div className="wea-search-wrap"  style={{display:showSearchAd?'block':'none'}}>
                                <Button type='ghost' className="wea-advanced-search" onClick={this.setShowSearchAd.bind(this,false)}>高级搜索</Button>
                                 <div className='wea-advanced-searchs' >
                                 <Form horizontal>
                                    {this.state.initialShowSearchAd && searchsBox}
                                     <div className="wea-search-buttons">
                                        <div style={{"textAlign":"center"}}>
                                        {this.state.initialShowSearchAd && buttonsAd && buttonsAd.map((data)=>{return (<span style={{marginLeft:15}}>{data}</span>)})}
                                        </div>
                                     </div>
                                    </Form>
                                 </div>
                            </div>
                            {showDropMenu && displayType === 'tree' &&
                                this.renderDropmenu()
                            }
                            <div >
                                <WeaNewScroll height={sheight} ref="weaSrcoll">
                                    {displayType === 'list' &&
                                        <WeaBrowserMutiLeft
                                            contentType = {contentType}
                                            inputId = {inputId}
                                            inputName = {inputName}
                                            inputTop = {inputTop}
                                            inputBottom = {inputBottom}
                                            onDoubleClick={this.onleftDoubleClick.bind(this)}
                                            onClick={this.onLeftListCheck.bind(this)}
                                            selectedKeys={leftListSelectedKeys}
                                            filterData={rightDatas}
                                            datas={listDatas}
                                        />
                                    }
                                    {displayType === 'tree' &&
                                        <WeaBrowserTree
                                            clickNodeExpandChildren
                                            type={type}
                                            browserTree={false}
                                            onDoubleClick={this.onleftTreeDoubleClick.bind(this)}
                                            checkable={true}
                                            topPrefix={topPrefix}
                                            dataUrl={dataUrl}
                                            checkedCb={this.onLeftTreeCheck.bind(this)}
                                            filterData={rightDatas}
                                            inputId = {inputId}
                                            inputName = {inputName}
                                            checkedDatas={leftTreeCheckedData}
                                            // componyParam={componyParam}
                                            // setData={this.setData.bind(this)}
                                            isMult={true}
                                            icon={icon}
                                            treeData={treeData}
                                            defaultExpandedKeys={defaultExpandedKeys}
                                            checkStrictly={checkStrictly}
                                            isLoadAll={loadAllTreeData}
                                            />
                                    }
                                </WeaNewScroll>
                            </div>
                            {
                                displayType === 'tree' &&
                                <Button className={`subordinates-icon ${showDropMenu? 'hasDropMenu': ''}`} size="small" title={'包含下级机构'} onClick={()=> {this.setState({checkStrictly: !checkStrictly})}}>
                                    <span>{!checkStrictly? <i className='icon-coms-DisplaySubordinates' style={{color: '#2db7f5'}}/> :<i className='icon-coms-NoDisplayOfSubordinates'/>}</span>
                                </Button>
                            }
                            {
                                (contentType === 1 || contentType === 4) &&
                                <Pagination
                                    weaSimple
                                    showTotal={total => `共${total}条`}
                                    total={count}
                                    pageSize={pageSize}
                                    current={currentPage}
                                    onChange={this.onPageChange.bind(this)}
                                />
                            }

                        </div>
                        <div className='wea-transfer-opration'>
                            <Operation
                              rightActive={rightActive}
                              leftActive={rightCheckedKeys && rightCheckedKeys.length > 0}
                              leftAllActive={leftAllActive}
                              rightAllActive={rightDatas && rightDatas.length > 0}
                              moveToRight={this.moveToRight}
                              moveToLeft={this.moveToLeft}
                              moveAllToRight={this.moveAllToRight}
                              moveAllToLeft={this.moveAllToLeft}
                            />
                        </div>
                        <div className='wea-hr-muti-input-right'>
                            <WeaBrowserMutiRight
                                ref="browserRight"
                                contentType = {contentType}
                                inputId = {inputId}
                                inputName = {inputName}
                                inputTop = {inputTop}
                                inputBottom = {inputBottom}
                                data={rightDatas}
                                checkedCb={this.onRightCheck.bind(this)}
                                onDoubleClick={this.onRightDoubleClick.bind(this)}
                                checkedKeys={rightCheckedKeys}
                                height={initHeight}
                                onDrag={(data) => {this.setState({rightDatas: data})}}
                            />
                        </div>
                    </div>
                </Spin>
            </Modal>
          </div>
        );
    }
    onLeftListCheck (keys, datas) {
        const {leftListSelectedData, inputId} = this.state;
        let targets = leftListSelectedData.concat(datas);
        targets = uniqBy(targets, inputId || 'id');
        targets = targets.filter((t) => keys.indexOf(t[inputId || 'id']) > -1);
        this.setState({
            leftListSelectedKeys: keys,
            leftListSelectedData: targets,
        })
    }
    onLeftTreeCheck (checkedKeys,datas) {
        this.setState({leftTreeCheckedKeys: checkedKeys, leftTreeCheckedData: datas});
    }
    onRightCheck (keys) {
        this.setState({rightCheckedKeys: keys});
    }
    throwCurrentState(ids, datas = []){
        const {inputName} = this.state;
        ids = uniq(ids.split(',')).join(',');
        this.setState({hiddenIds: ids});
        let names = [];
        datas.forEach((d) => {
            names.push(d[inputName + 'span'] || d[inputName]);
        });
        this.props.onChange && this.props.onChange(ids, names.join(','), datas);
    }

    getSearchs(){
        const {browserConditions} = this.state;
        let items = [];
        !isEmpty(browserConditions)&& browserConditions.forEach( field => {
            items.push({
                com:(<FormItem
                    label={`${field.label}`}
                    labelCol={{span: `${field.labelcol}`}}
                    wrapperCol={{span: `${field.fieldcol}`}}>
                        {WeaTools.getComponent(field.conditionType, field.browserConditionParam, field.domkey,this.props, field)}
                    </FormItem>),
                colSpan: 1,
                hide: WeaTools.isComponentHide(field),
            });
        });
        return <WeaSearchBrowserBox items={items} />
    }

    getTabButtonsAd() {
        let _this = this;
        const {resetFields,validateFields} = this.props.form;
        return [
            <Button type="primary" onClick={(e)=>{this.goSearch(e)}}>搜索</Button>,
            <Button type="ghost" onClick={(e)=>{this.reset()}}>重置</Button>,
            <Button type="ghost" onClick={()=>{_this.setState({showSearchAd:false})}}>取消</Button>
        ]
    }
}

let conditionParamsBK={};
Main = Form.create({
    onFieldsChange(props, fields){
        for(let key in fields) {
            conditionParamsBK[fields[key].name] = fields[key].value
        }
    }
})(Main);
export default Main;